import * as path from "path";
import { WsServer } from "tsrpc";
import { Room } from "./shared/Room";
import { RoomServer } from "./models/RoomServer";
import { serviceProto } from './shared/protocols/serviceProto';
import { CurrentUser } from "./shared/types/CurrentUser";

// Create the Server
export const server = new WsServer(serviceProto, {
    port: 3000,
    // Remove this to use binary mode (remove from the client too)
    json: true,
    // 超过 10 秒未收到心跳包，则断开该连接
    // 注意，这个值需要大于客户端的 heartbeat.interval（2倍以上为宜）
    heartbeatWaitTime: 10000,
    // Enable this to see send/recv message details
    logMsg: false,
});
export const roomServer = new RoomServer();

// Initialize before server start
async function init() {
    await server.autoImplementApi(path.resolve(__dirname, 'api'));

    // TODO
    // Prepare something... (e.g. connect the db)
};

// Entry function
async function main() {
    await init();
    await server.start();
}
main();

// 扩展 Connection 字段
declare module 'tsrpc' {
    export interface BaseConnection {
        currentUser: CurrentUser,
        room?: Room,
    }
}